package DB;

import Model.Product;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Tomas
 */
public class ProductManager implements IFProductManager{

    private Connection con;

    public ProductManager(){
        con = DBConnector.getInstance().getDBConnection();
    }

    public Product getProduct(int productId, boolean retrieveAssociations) {
        String param = ""+productId;
        return singleWhere("productId = ?",new String[]{param},retrieveAssociations);
    }
    private Product singleWhere(String whereC, String[] params, boolean assoc){
        ResultSet results;
        String query = buildQuery(whereC);
        Product resultProduct = null;
        try{
            PreparedStatement stmt = con.prepareStatement(query);
            for(int a = 0; a < params.length; a++){
              stmt.setString(a+1, params[a]);
            }
            stmt.setQueryTimeout(5);
            results = stmt.executeQuery();
            if(results.next()){
                resultProduct = buildProduct(results);
            }
            stmt.close();

        }catch(Exception e){
            System.out.println(e.getMessage());
        }
       if(resultProduct == null){
            throw new IllegalArgumentException("Product not found");
        }
        return resultProduct;
    }
        private String buildQuery(String whereC){
        String query = "SELECT * FROM Product";
        if(!whereC.isEmpty()){
            query = query+" WHERE "+whereC;
        }
        return query;
    }
    private Product buildProduct(ResultSet resSet){
        Product product = null;
        try {
            product = new Product(resSet.getInt(1));
            product.setName(resSet.getString(2));
            product.setPrice(resSet.getFloat(4));
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return product;
    }
}
